package common

import (
	"database/sql/driver"
	"log"
	"time"
)

const (
	//DateFormat = "2006-01-02"
	TimeFormat = "2006-01-02 15:04:05"
)

type Time time.Time

func Now() Time {
	return Time(time.Now())
}

func (t *Time) UnmarshalJSON(data []byte) (err error) {
	v := string(data)
	now, err := time.ParseInLocation(`"`+TimeFormat+`"`, v, time.Local)
	*t = Time(now)
	return err
}

func (t Time) MarshalJSON() ([]byte, error) {
	b := make([]byte, 0, len(TimeFormat)+2)
	b = append(b, '"')
	b = time.Time(t).AppendFormat(b, TimeFormat)
	b = append(b, '"')
	return b, nil
}
func (t Time) String() string {
	return time.Time(t).Format(TimeFormat)
}

type NullTime struct {
	Time  time.Time
	Valid bool // Valid is true if Time is not NULL
}

// Scan implements the Scanner interface.
func (nt *NullTime) Scan(value interface{}) error {
	nt.Time, nt.Valid = value.(time.Time)
	return nil
}

// Value implements the driver Valuer interface.
func (nt *NullTime) Value() (driver.Value, error) {
	if !nt.Valid {
		return nil, nil
	}
	return nt.Time, nil
}

func (nt *NullTime) String() string {
	return nt.Time.String()
}

//  Json反序列化
//  如果反编译失败  Valid 为false 表示时间为Null
func (nt *NullTime) UnmarshalJSON(data []byte) (err error) {
	v := string(data)
	log.Println("v:" + v)
	now, err := time.ParseInLocation(`"`+TimeFormat+`"`, v, time.Local)
	log.Println(err)
	if err != nil {
		log.Println(err)
		*nt = NullTime{Valid: false}
		return nil
	}
	*nt = NullTime{Time: time.Time(now), Valid: true}
	return nil
}

// Json 序列化函数
// 如果Valid为 false 则序列化为空
func (nt NullTime) MarshalJSON() ([]byte, error) {
	b := make([]byte, 0, len(TimeFormat)+2)
	if nt.Valid {
		b = append(b, '"')
		b = time.Time(nt.Time).AppendFormat(b, TimeFormat)
		b = append(b, '"')
	} else {
		b = append(b, '"')
		b = append(b, '"')
	}

	return b, nil
}
